<?php
class SecuredSession extends CApplicationComponent
{
    private $_namespace = 'secured_namespace';
    
    public function init()
    {
	parent::init();
	$this->open();
    }

    private function open()
    {
		Yii::app()->session; // auto start
    }

    public function get($key, $defaultValue=null)
    {
		$this->securityCheck();
		return isset($_SESSION[$this->_namespace][$key]) ? $_SESSION[$this->_namespace][$key] : $defaultValue;
    }
    
    private function securityCheck()
    {
		if (isset($_SESSION[$this->_namespace]['ip']) && $_SESSION[$this->_namespace]['ip'] != Yii::app()->request->getUserHostAddress()) {
			$this->clear();
			throw new CException('Your IP was changed.');
		}
    }

    public function set($key, $value)
    {
		$_SESSION[$this->_namespace][$key] = $value;
		$_SESSION[$this->_namespace]['ip'] = Yii::app()->request->getUserHostAddress(); 
    }

    public function remove($key)
    {
		$this->securityCheck();
		if(isset($_SESSION[$this->_namespace][$key])) {
			unset($_SESSION[$this->_namespace][$key]);
		}
    }
    
    public function clear()
    {
		foreach(array_keys($_SESSION[$this->_namespace]) as $key)
			unset($_SESSION[$this->_namespace][$key]);
    }
}